package com.aptemo.webetek.server.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.server.CommonService;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.server.datastore.DataStoreHelper;
import com.aptemo.webetek.server.datastore.DataStoreImpl;
import com.aptemo.webetek.shared.BetBean;
import com.aptemo.webetek.shared.PickBean;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * The server side implementation of the Invitation service.
 */
public class CheckBetsService
		extends HttpServlet
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 2442498766498504653L;

	/**
	 * 
	 */
	private UserService			userService			= UserServiceFactory.getUserService();

	private DataStoreHelper		dataHelper			= new DataStoreHelper();

	private DataStoreAPI		dataService			= new DataStoreImpl();

	private CommonService		utils				= new CommonService();

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		boolean writemode = false;
		int limit = 10;

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		String url = req.getRequestURI().toString();
		String queryString = req.getQueryString();
		if (queryString != null)
		{
			url += "?" + queryString;
		}

		String userId = req.getParameter("userId");
		String tresholdPar = req.getParameter("treshold");
		String statusPar = req.getParameter("status");
		String silentPar = req.getParameter("write");
		String limitPar = req.getParameter("limit");

		Key tk = KeyFactory.stringToKey(userId).getParent();
		String teamId = KeyFactory.keyToString(tk);

		try
		{
			limit = Integer.parseInt(limitPar);
		}
		catch (Exception e1)
		{
			e1.printStackTrace();
			limit = 10;
		}

		try
		{
			writemode = Boolean.parseBoolean(silentPar);
		}
		catch (Exception e1)
		{
			e1.printStackTrace();
			writemode = false;
		}
		// convert
		DateFormat df = new SimpleDateFormat();
		Date treshold;
		try
		{
			treshold = df.parse(tresholdPar);
		}
		catch (Exception e1)
		{
			e1.printStackTrace();

			treshold = new Date();
		}

		// 
		// EnumEventStatus status = EnumEventStatus.valueOf(statusPar);

		String loginUrl = userService.createLoginURL(url);
		if (!userService.isUserLoggedIn() && !userService.isUserAdmin())
		{
			res.sendRedirect(loginUrl);
			return;
		}

		// 
		String redirect = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{

			List<BetBean> stakes = dataService.getBets(userId, null);

			// List<Stake> stakes = user.getStakes();

			String content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
			content += "<html><head><title>Online betting with Webetek</title></head>";
			content += "<body>";

			content += "User: " + dataService.getPlayer(userId).getEmail() + " (" + dataService.getTeam(teamId).getName() + ")" + "<br/>";

			for (BetBean stake : stakes)
			{
				content += "=========================Event " + stake.getDate() + "===============================<br/>";
				// update pick count and calculate sum
				content += "id: " + stake.getId();
				content += "<br/>";
				content += "amount: " + stake.getAmount();
				content += "<br/>";
				content += "earnings: " + stake.getEarnings();
				content += "<br/>";
				// content += "won count: " + stake.getWonCnt();
				// content += "<br/>";
				content += "totalOdds: " + stake.getTotalOdds();
				content += "<br/>";

				content += "picks: <br/>";
				List<String> ids = new ArrayList<String>();
				for (PickBean pick : stake.getPicks())
				{
					if (ids.contains(pick.getEventKey()))
					{
						content += "<b>!!!!!!!!!!!!!!!!!!</b>";
					}
					ids.add(pick.getEventKey());
					content += pick.getTitle() + " => " + pick.getId();
					content += "<br/>";
				}
				content += "<br/>";

			}
			content += "</body>";
			content += "</html>";

			out.println(content);
		}
		catch (BackendException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			out.close();
			pm.close();
		}

		// TODO....
		// res.sendRedirect("error");
	}
}
